// 服务层代码
const Comments = require('../models/Comments')
const Posts = require('../models/Post')
const redis = require('../config/redis')
const { commentListAdmin } = require('../attributes/comment')
const { Op, col } = require('sequelize')
const dayjs = require('dayjs')

async function getCommentsWithCache(postId) {
  // const cacheKey = `post:comments:tree:${postId}`;

  // // 1. 尝试从Redis获取
  // const cached = await redis.get(cacheKey);
  // if (cached) {
  //    return JSON.parse(cached);
  // }
  //  缓存未命中，查询数据库
  const comments = await fetchCommentTreeFromDB(postId)
  //  写入Redis（带过期时间）
  // await redis.setex(
  // cacheKey,
  // 3600, // 1小时过期
  // JSON.stringify({
  //    comments,
  //    expiresAt: Math.floor(Date.now() / 1000) + 3600
  // }));
  return comments
}

// 客户端展示评论
async function fetchCommentTreeFromDB(postId) {
  const comments = await Comments.findAndCountAll({
    attributes: [
      'id',
      'nickname',
      'content',
      'createdAt',
      'avatar',
      'postId',
      'parentId',
      'level',
      'postId',
      [col('parentComment.nickname'), 'replyName'],
      [col('parentComment.avatar'), 'replyAvatar'],
      [col('post.title'), 'title'],
    ],
    include: [
      {
        model: Comments,
        as: 'parentComment',
        attributes: [],
        required: false,
      },
      {
        model: Posts,
        attributes: [],
        where: { id: postId },
        required: true,
      },
    ],
    where: {
      postId: postId,
      status: 'approved',
    },
    order: [['createdAt', 'DESC']],
  })
  // 递归处理评论树结构
  return {
    comments: buildNestedCommentTree(comments.rows),
    total: comments.count,
  }
}

// 管理系统评论展示
async function fetchVisitorComments(pageSize, offset, where) {
  const result = await Comments.findAll({
    attributes: [
      'id',
      'nickname',
      'content',
      'avatar',
      'createdAt',
      'status',
      'parentId',
      'postId',
      [col('Parent.content'), 'toContent'],
      [col('Parent.nickname'), 'toNickname'],
      [col('Parent.avatar'), 'toAvatar'],
      [col('post.title'), 'articleTitle'],
    ],
    include: [
      {
        model: Comments,
        as: 'Parent',
        attributes: [], // 不返回关联模型的所有字段
        required: false, // LEFT JOIN
      },
      {
        model: Posts,
        attributes: [], // 不返回关联模型的所有字段
        required: false, // LEFT JOIN
      },
    ],
    where,
    limit: pageSize,
    offset,
    order: [['createdAt', 'DESC']],
    raw: true, // 返回纯JSON数据
  })
  return result
}

/**
 * 构建评论树形结构 【用户端】
 * @param flatComments
 * @returns {*|*[]}
 */
function buildNestedCommentTree(flatComments) {
  if (!flatComments || flatComments.length === 0) {
    return []
  }
  function buildCommentTree(comments, parentId = null) {
    return comments
      .filter((comment) => comment.parentId === parentId)
      .map((comment) => {
        // 找到父级评论信息（如果有）
        const parentComment = parentId ? comments.find((c) => c.id === parentId) : null
        // 构建当前节点
        const node = {
          id: comment.id,
          content: comment.content,
          nickname: comment.nickname,
          createdAt: dayjs(comment.createdAt).format('YYYY-MM-DD HH:mm:ss'),
          avatar: comment.avatar || null,
          parentId: comment.parentId,
          replyName: comment.replyName || null,
          replyAvatar: comment.replyAvatar || null,
          parentComment: parentComment
            ? {
                id: parentComment.id,
                nickname: parentComment.nickname,
                avatar: parentComment.avatar || null,
              }
            : null,
          children: [], // 初始化空children数组
        }
        // 递归构建子节点
        node.children = buildCommentTree(comments, node.id)
        return node
      })
  }

  return buildCommentTree(flatComments)
}

module.exports = {
  getCommentsWithCache,
  fetchVisitorComments,
}
